package springcloud.controller;

import edu.neu.springcloud.entity.Commodity;
import edu.neu.springcloud.entity.CommodityVo;
import edu.neu.springcloud.entity.Factory;
import edu.neu.springcloud.service.CommodityClientService;
import edu.neu.springcloud.service.FactoryClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@RestController
public class FactoryConsumerController {
    @Autowired
    private CommodityClientService commodityClientService;

    @Autowired
    private FactoryClientService factoryClientService;

    @GetMapping("/list")
    public List<Factory> list(@RequestParam(value = "id", required = false) Long id,
                                  @RequestParam(value = "name", required = false) String name) {
        return factoryClientService.getAll(id, name);
    }

    @PostMapping("/add")
    public boolean add(@RequestBody Factory factory) {
        return factoryClientService.add(factory);
    }

    @PostMapping("/update")
    public boolean update(@RequestBody Factory factory) {
        return factoryClientService.update(factory);
    }

    @GetMapping("/delete/{id}")
    public boolean delete(@PathVariable("id") Long id) {
        // 级联删除，先删除属于此工厂的所有商品
        List<Commodity> commodityList = commodityClientService.getAll(null, id, null, null);
        for (Commodity c : commodityList) {
            commodityClientService.delete(c.getId());
        }
        // 最后删除工厂
        return factoryClientService.delete(id);
    }

}
